#include "JSP.h"

#include <iostream>	//cout,cin
#include <cstdlib> 	//exit
#include <cstring>	
using namespace std;
JSP::JSP(const char * file)
{
	name = new char[20];
	type = new char[20];
	format = new char[20];
	
	filename = file;
	ReadFile();
}
JSP::~JSP()
{
	delete [] name;
	delete [] type;
	delete [] format;
	delete [] task;
	delete [] schedule;
}
void JSP::ReadFile()
{
	FILE * fin = fopen(filename, "r");
	if(fin != NULL)
	{	
		FindKeywords(fin);
		ReadData(fin);
		fclose(fin);
	}
	else
	{
		perror(filename);
		cout <<"Press any key to exit.."<<endl;
		getchar();
		exit(1);
	}
}
void JSP::ReadData(FILE *fin)
{
	if(charncmp("orlib", format) )
	{
		task = new int[machines *2* jobs];
		if(task == NULL)
		{	
			perror("Unable to allocate tash[machines*jobs] array");
			exit(1);
		}
		
		//cout << "chars red :"<<fread(task,	4, machines*jobs, fin);
		for(int i=0; i < machines*2 * jobs; i++)
		{
			fscanf(fin, "%u", &task[i]);
		}
	}
}
void JSP::FindKeywords(FILE *fin)
{
	char line[128];	
	while(fgets(line,sizeof line,fin) != NULL)
	{
		strtok(line," :");
		if(charncmp("NAME",line))
		{	
			strcopy(name, strtok(NULL," :"));
			continue;
		}
		if(charncmp("TYPE",line))
		{	
			strcopy(type,strtok(NULL," :"));
			continue;
		}
		if(charncmp("FORMAT",line))
		{	
			strcopy(format,strtok(NULL," :"));
			continue;
		}
		if(charncmp("JOBS",line))
		{	
			jobs = atoi( strtok(NULL," :"));
			continue;
		}
		if(charncmp("MACHINES",line))
		{	
			machines = atoi( strtok(NULL," :"));
			continue;
		}
		if(charncmp("NODE_DATA_SECTION",line))
			break;
	}
}
bool JSP::CheckCompatibility()
{
	if(charncmp("jobshop",type) )
	   return true;
	perror("Only jobshop is supported.\nPress a key to exit.");
	return false;
}
void JSP::Print()
{
	cout << "Name:" 	<< name 	<<endl;
	cout << "Type:" 	<< type 	<<endl;
	cout << "Format:" 	<< format 	<<endl;
	cout << "machines:" << machines <<endl;
	cout << "jobs:" 	<< jobs 	<<endl;
	
	for(int i=0; i < machines*2 * jobs; i++)
	{
		if( i%(machines*2) == 0)
			cout << endl;
		cout << task[i]<< " ";
	}
}
bool JSP::charncmp(const char *c1,const char *c2)
{	
	if(strncmp(c1,c2,strlen(c1)) == 0)
		return true;
	return false;
}
void JSP::strcopy( char * dest,char * src)
{
	for (int i = 0; i < (int)strlen(src); ++i )
        if ( src[i] == '\n' )
            src[i] = '\0';
	strncpy(dest,src,strlen(src)+1); //+1 за да се копира и \n
}
